<?php
/*华为*/

namespace App\Tools;

use App\Tools\Curl;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Log;

class Huawei
{

    protected $curl;
    protected $header = [];
    protected $url = 'https://connect-api.cloud.huawei.com/api/datasource/v1/track/activate';
    protected $tokenUrl = 'https://connect-api.cloud.huawei.com/api/oauth2/v1/token';

    protected $appId = '107176777';
    protected $clientId = '1029627705001266304';
    protected $clientSecret = '1E6D5C56C5803D6F5ECCE41A48B4986656E36161512917540D4F3EB9C6806081';

    const HUAWEI_TOKEN_KEY = "HUAWEI:TOKEN"; //hash
    
    public function __construct()
    {
        $this->curl = new Curl();

        $this->header['client_id'] = $this->clientId;
        $this->header['Authorization'] = "Bearer " . $this->getAccessToken();
    }

    //获取accessToken
    public function getAccessToken()
    {
        $tokenInfo = Redis::hget(self::HUAWEI_TOKEN_KEY, 'expires_in') ?? 0;
        if ($tokenInfo && time() <= $tokenInfo) {
            return Redis::hget(self::HUAWEI_TOKEN_KEY, 'access_token');
        }

        $param = [
            'grant_type' => 'client_credentials',
            'client_id' => $this->clientId,
            'client_secret' => $this->clientSecret
        ];
        $res = $this->curl->curl_request($this->tokenUrl, $param, 'json', 'POST');
        if (isset($res['ret'])) {
            //Log::info(__METHOD__, ['ret' => $res['ret']]);
            return '';
        }

        Redis::hmset(self::HUAWEI_TOKEN_KEY, 'expires_in', time() + $res['expires_in'], 'access_token', $res['access_token']);
        return $res['access_token'];
    }

    /**
     * @desc 回传用户行为数据
     * @param $actionType 1:激活 7:注册 4:付费
     */ 
    public function dataRetrieval($actionType, $oaid, $callback)
    {
        $param = [
            'appId' => $this->appId,
            'deviceIdType' => 'OAID',
            'deviceId' => $oaid,
            'actionTime' => time() . '000',
            'actionType' => $actionType,
            'callBack' => $callback,
            // 'callBack' => 'security:4053FFBAAE7109AE51C6DF9A:D0A9FB392680FE8F2BD82C1215873DF84A6C5F5EEE3CBCCA4D56F65F8A08E9DC481BC0BBBDAA0666FD30B8D07CD21A',
        ];
        $res = $this->curl->curl_request($this->url, $param, 'json', 'POST', $this->header);
        //Log::info(__METHOD__, ['oaid' => $oaid, 'callBack' => $callback]);
        //Log::info(__METHOD__, [$res]);
    }
}